package pl.controller.Captcha;

import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.reading.CaptchaReader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.xml.sax.SAXException;

import pl.common.SessionDataBean;

@Controller
public class Captcha {
	
	protected final Log log = LogFactory.getLog(getClass());
	protected CaptchaReader reader;
	protected Parameters parameters;

	@RequestMapping("/captcha.htm")
    public ModelAndView captcha(HttpServletRequest request, HttpServletResponse response) throws IOException{
    	
    	log.info("before captcha");
    	
    	response.setContentType("image/jpeg");  
	
    	HttpSession session = request.getSession();
    	log.debug("session: " + session);
    	SessionDataBean data = (SessionDataBean) session.getAttribute("sessionData");
    	
    	log.info("sessionData: " + data);
    	
    	if (data == null){
    		throw new IllegalStateException("probably session timeout");
    	}
    	
    	generateCaptcha(data.getCaptcha(), response.getOutputStream());
    	
    	log.info("generatedCaptcha");
    	
		response.getOutputStream().flush();
		
		
   // 	response.getWriter().append("executed").flush();
		
    	return null;
    }

	private void generateCaptcha(String captcha,
			ServletOutputStream outputStream) {
		try {
			log.debug("generateCaptcha start " + captcha);
			if (reader == null){
				reader = new CaptchaReader();
				parameters = new Parameters();
		parameters.setParameter("width", "100");
		parameters.setParameter("height", "50");
				
			}
			reader.setOutputStream(outputStream);
			try {
				reader.setup(null, null, captcha, parameters);
				reader.generate();
			} catch (ProcessingException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			log.debug("generateCaptcha end");
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		
	}
}
